<template>
  <div class="alarm-info-maintain">
    <el-row style="paddingBottom: 0">
      <el-col :span="24">
        <dynForm :info-form="infoForm" :search-tags="searchTags" :select-list="selectList">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="doSearch">
            {{ $t("search") }}
          </el-button>
        </dynForm>
      </el-col>
    </el-row>
    <div class="table-buttons">
      <!-- v-btnPermission:add -->
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="newAdd"
      >{{ $t("add") }}</el-button
      >
      <!-- v-btnPermission:edit -->
      <el-button
        :disabled="UpdateDisabled"
        type="primary"
        icon="el-icon-edit"
        @click="doModify"
      >{{ $t("modify") }}</el-button
      >
      <!-- v-btnPermission:delete -->
      <el-button
        :disabled="DeleteDisabled"
        type="danger"
        icon="el-icon-delete"
        @click="doDelete"
      >{{ $t("delete") }}</el-button
      >
      <!-- @click="doDelete" -->
      <!-- v-btnPermission:add -->
      <el-button
        type="primary"
        icon="el-icon-download"
        @click="downloadFile"
      >{{ $t("downloadTemp") }}</el-button>
      <el-upload
        :action="baseApi + '/ams/upload/submit?name=AlarmInfoExcelList'"
        :headers="headers"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :on-error="importFail"
        class="upload-btn"
        style="display: inline-block"
        accept=".xlsx"
      >
        <!-- v-btnPermission:add -->
        <el-button
          type="primary"
          icon="el-icon-upload"
        >{{ $t("import") }}</el-button>
      </el-upload>
      <!-- v-btnPermission:add -->
      <el-button
        type="primary"
        icon="el-icon-download"
        @click="doExport"
      >{{ $t("export") }}
      </el-button>
    </div>
    <el-card shadow="never">
      <el-row>
        <dynTable
          ref="dynTable"
          :loading="tableLoading"
          :table-data="tableData"
          :table-columns="tableColumns"
          :handle-selection-change="handleSelectionChange"
          :row-click="rowClick"
        />
      </el-row>
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        @pagination="getList"
      />
    </el-card>
    <codeMaintainForm ref="codeMaintainForm" @initList="initList"/>
    <recordModel ref="recordModel" />
  </div>
</template>

<script>
import mySetting from '@/mixins/mySetting'
import { getList, download, handleDelete } from '@/api/alarm/codeMaintain'
import { mapGetters } from 'vuex'
import { getEqpModelList } from '@/api/equipment/eqpbase'
import codeMaintainForm from './components/codeMaintainForm'
import recordModel from './components/recordModel.vue'
import { getToken } from '@/utils/auth'
export default {
  name: 'AlarmCodeMaintain',
  components: { codeMaintainForm, recordModel },
  mixins: [mySetting],
  data() {
    return {
      infoForm: {},
      searchTags: [
        { label: this.$t('eqpId'), prop: 'eqpId', tag: 'DynInput', labelwidth: '90px' },
        // { label: this.$t('eqpModel'), prop: 'eqpModel', tag: 'DynSelect', labelwidth: '90px' },
        { label: this.$t('AlarmCode'), prop: 'alarmId', tag: 'DynInput' },
        { label: this.$t('is_collect_alarms'), prop: 'isSave', tag: 'DynSelect' },
        { label: this.$t('alarmDescription'), prop: 'description', tag: 'DynInput' }
      ],
      selectList: {
        isSave: [{ id: 1, name: this.$t('yes') }, { id: 2, name: this.$t('no') }]
      },
      tableColumns: Object.freeze([
        { prop: '', label: '', type: 'selection' },
        { prop: '', label: this.$t('index'), type: 'index', width: '50px', templete: (_scope) => {
          return (
            <span>{ (this.listQuery.page - 1) * this.listQuery.size + _scope.$index + 1 }</span>
          )
        } },
        { prop: 'eqpId', label: this.$t('eqpId') },
        // { prop: 'eqpModel', label: this.$t('eqpModel') },
        { prop: 'alarmID', label: this.$t('AlarmCode') },
        { prop: 'alarmDesc', label: this.$t('alarmDescription'), width: '200px' },
        // { prop: 'mtba', label: this.$t('MTBAOrNot'), templete: (_scope) => {
        //   return (
        //     <el-switch
        //       v-model={_scope.row.mtba}
        //       active-value={1}
        //       inactive-value={0}
        //       active-color={'#13ce66'}
        //       inactive-color={'#ff4949'}
        //       disabled/>
        //   )
        // } },
        // { prop: 'alarmLevel', label: this.$t('AlarmLevel') },
        { prop: 'isSave', label: this.$t('is_collect_alarms'), width: '120px', templete: (_scope) => {
          return (
            <el-switch
              v-model={_scope.row.isSave}
              active-value={1}
              inactive-value={0}
              active-color={'#13ce66'}
              inactive-color={'#ff4949'}
              disabled/>
          )
        } },
        { prop: 'isEqpAlarm', label: this.$t('IsSelfAlarm'), width: '120px', templete: (_scope) => {
          return (
            <el-switch
              v-model={_scope.row.isEqpAlarm}
              active-value={1}
              inactive-value={0}
              active-color={'#13ce66'}
              inactive-color={'#ff4949'}
              disabled/>
          )
        } },
        { prop: 'mtba', label: this.$t('MTBAOrNot'), width: '120px', templete: (_scope) => {
          return (
            <el-switch
              v-model={_scope.row.mtba}
              active-value={1}
              inactive-value={0}
              active-color={'#13ce66'}
              inactive-color={'#ff4949'}
              disabled/>
          )
        } },
        { prop: 'createTime', label: this.$t('createTime') },
        { prop: 'editTime', label: this.$t('editeTime') },
        { prop: '', label: this.$t('modifyHistory'), fixed: 'right', width: '80px', templete: (_scope) => {
          return (
            <el-button type='text' size='small'
              onclick={() => this.handleViewClick(_scope.row)}>
              {this.$t('modifyHistory')}</el-button>
          )
        } }
      ]),
      tableLoading: true,
      headers: {
        Token: getToken()
      }
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  created() {
    // this.getEqpModelsList()
    this.initList()
  },
  methods: {
    doSearch() {
      this.listQuery.page = 1
      this.initList()
    },
    async initList() {
      this.tableLoading = true
      const res = await getList(this.$clearNull({ ...this.infoForm, ...this.listQuery }))
      this.tableData = res.data
      this.total = res.total
      this.tableLoading = false
    },
    handleViewClick(row) {
      this.$refs.recordModel.handleOpen(row)
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    rowClick(row) {
      this.$refs.dynTable.$refs.multipleTable.toggleRowSelection(row)
    },
    newAdd() {
      this.$refs.codeMaintainForm.handleOpen()
    },
    doModify() {
      this.$refs.codeMaintainForm.handleOpen(this.multipleSelection[0])
    },
    doDelete() {
      this.$confirm(
        `${this.$t('confirmDelete')}${this.multipleSelection.length}${this.$t(
          'recordCount'
        )}?`,
        this.$t('tip'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).then(() => {
        const ids = this.multipleSelection.map((ele) => ele.id)
        handleDelete({ ids }).then((res) => {
          this.$betterTips(res, this.setOnePage, this.initList)
        })
      })
    },
    getList(value) {
      this.listQuery = value
      this.initList()
    },
    uploadSuccess(response, file, fileList) {
      // 第{ele.index}行 {this.$t(ele.msgCode)}
      // 第{ele.split(',')[0]}行 {this.$t(ele.split(',')[1])}
      // this.netTips(response.code)
      if (response.code !== 1) {
        const h = this.$createElement
        let listVNode
        if (response.data instanceof Array) {
          listVNode = response.data.map((item) => {
            return (
              <p style={ { width: '240px' }}>
                <span style={ { width: '100%', wordWrap: 'break-word' }}>{item.index ? `第{${item.index}}行` : ''}{this.$t(item.msgCode)}</span>
              </p>
            )
          })
          const styles = {
            color: 'teal',
            overflowX: 'hidden',
            overflowY: 'auto',
            width: '280px',
            maxHeight: 'calc(100vh - 120px)'
          }
          this.$notify({
            message: h('div', { style: styles }, listVNode),
            type: 'error',
            duration: 0
          })
        } else {
          this.$betterTips(response)
        }
        fileList = []
      } else {
        this.$betterTips(response, this.initList)
      }
    },
    importFail() {
      this.$notify({
        message: this.$t('uploadFail'),
        type: 'error',
        duration: 3500
      })
    },
    async downloadFile() {
      download({ name: 'AlarmInfoExcelList' }).then((res) => {
        window.open(this.baseApi + '/' + res.data)
      })
    },
    async doExport() {
      const obj = {
        ...this.infoForm,
        ...this.listQuery,
        toexcel: 1
      }
      const res = await getList(this.$clearNull(obj))
      if (res.code === 1) {
        window.location.href = this.baseApi + '/' + res.data
      } else {
        this.$betterTips(res)
      }
    },
    async getEqpModelsList() {
      const res = await getEqpModelList()
      this.$set(this.selectList, 'eqpModel', res.data)
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/styles/defaultStyle.scss";
.upload-btn{
  margin: 0 10px;
}
</style>
